﻿Module Module1

    Sub Main()

        '使用特性和反射的方法是：
        '使用Attribute类来声明要使用的特性，它继承自Attribute类
        '使用GetCustomAttributes方法来获取声明的特性
        '使用Type.GetType方法来获取类型的实例
        '使用Type.GetMembers方法获取类型的成员
        '使用MemberInfo.GetCustomAttributes方法来获取特性

        Dim sc As SampleClass = New SampleClass
        Dim sct = sc.GetType()
        PrintAuthorInfo2(sct)





        '返回一个数组
        Dim ms As Reflection.MemberInfo() = sct.GetMethods()
        For Each m As Reflection.MemberInfo In ms
            Console.WriteLine("方法名:{0}", m.Name)
            Dim vs() As Object = m.GetCustomAttributes(False)
            For Each v As Object In vs
                If v.GetType = Type.GetType("ConsoleApp6.Module1+Author") Then
                    Console.WriteLine(v.ToString())  'ConsoleApp6.Module1+Author
                    Console.WriteLine("作者:{0},版本:version {1:f}", v.GetName(), v.version)
                End If
            Next

        Next



        Console.ReadKey()

    End Sub

    Private Sub PrintAuthorInfo(ByVal t As Type)
        Console.WriteLine("Author information for {0}", t)
        Dim attrs() As Attribute = Attribute.GetCustomAttributes(t)
        For Each attr In attrs
            Dim a As Author = CType(attr, Author)
            Console.WriteLine("作者:{0},版本:version {1:f}", a.GetName(), a.version)
        Next
    End Sub

    Private Sub PrintAuthorInfo2(ByVal t As Type)
        Console.WriteLine("Author information for {0}", t)
        Dim attrs() As Author = t.GetCustomAttributes(Type.GetType("ConsoleApp6.Module1+Author"), False)
        For Each a In attrs
            Console.WriteLine("作者:{0},版本:version {1:f}", a.GetName(), a.version)
        Next
    End Sub




    '<AttributeUsage(AttributeTargets.Class Or
    '                   AttributeTargets.Struct,
    '                   AllowMultiple:=True)>

    <AttributeUsage(AttributeTargets.All, AllowMultiple:=True, Inherited:=False)>
    Public Class Author : Inherits Attribute
        Private name As String
        Public version As Double
        Sub New(ByVal authorName As String)
            name = authorName
            version = 1.0
        End Sub

        Function GetName() As String
            Return name
        End Function
    End Class

    <Author("P. Ackerman")>
    Public Class SampleClass

        <Author("叶静")>
        Public Function Say()
            Console.WriteLine("hello sampleClass")
        End Function
    End Class


End Module
